package com.tct.worktimeboard.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tct.worktimeboard.config.DataSourceEnum;
import com.tct.worktimeboard.entity.Project;
import com.tct.worktimeboard.entity.User;
import com.tct.worktimeboard.log.DataSource;
import com.tct.worktimeboard.mapper.ProjectMapper;
import com.tct.worktimeboard.mapper.UserMapper;
import com.tct.worktimeboard.service.IProjectService;
import com.tct.worktimeboard.util.JsonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Huhailong
 * @Description
 * @Date 2021/2/22.
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project>  implements IProjectService {

    @Resource
    ProjectMapper projectMapper;
    @Resource
    UserMapper userMapper;

    /**
     * 默认使用db1数据源测试
     * @return 返回项目数据
     */
    @Override
    public JSONObject getProject() {
        return JsonUtil.toJsonData(projectMapper.selectList(null));
    }

    /**
     * 动态切换db2数据源测试
     * @return 返回用户数据
     */
    @DataSource(DataSourceEnum.DB2)
    @Override
    public List<User> getUser() {
        return userMapper.selectList(null);
    }

    @Override
    public JSONObject listPagePro(Project project) {
        if(project.isPaged()){
            PageHelper.startPage(project.getPageNum(),project.getPageSize());
        }
        QueryWrapper<Project> queryWrapper = new QueryWrapper<>();
        if(project.getProjectTypeId() != null){
            queryWrapper.eq("project_type_id",project.getProjectTypeId());
        }
        if(project.getProjectName() != null && !project.getProjectName().isEmpty()){
            queryWrapper.like("project_name",project.getProjectName());
        }
        List<Project> list = projectMapper.selectList(queryWrapper.orderByDesc("create_time"));
        PageInfo<Project> info = new PageInfo<>(list);
        Map<String, Object> result = new HashMap<>();
        result.put("total",info.getTotal());
        result.put("rows",list);
        return JsonUtil.toJsonData(result);
    }
}
